package com.hbcj.dlts.controller;

import com.hbcj.dlts.Form;
import freemarker.template.Configuration;
import freemarker.template.Template;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import org.apache.commons.beanutils.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;

import java.io.*;
import java.lang.reflect.InvocationTargetException;
import java.util.*;

@RequestMapping("/fm")
@Controller
public class FreeMarkerController {

    private Logger Log = LoggerFactory.getLogger(FreeMarkerController.class);

    @Autowired
    private FreeMarkerConfigurer freeMarkerConfigurer;

    @Autowired
    private Configuration configuration;

    @Value("${pagedir}")
    private String pagedir;

    @GetMapping("/hello")
    public String hello(Model model) {
        model.addAttribute("hello", "<h1>Hello FreeMarker"+pagedir+"</h1>");
        return "hello";
    }

    public static Map<String, String> objectToMap(Object object){
        try {
            Map<String, String> dataMap = BeanUtils.describe(object);
            dataMap.remove("class");//移除多出来的class字段
            return dataMap;
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        }
        return new HashMap<>();
    }



    //通过表单的传值，获取需要替换的属性，更换百度seo相关参数

    @RequestMapping(value="/genHtml",method = RequestMethod.POST)
    @ResponseBody
    public String test( Form form)  {
        try {
            //获取模板
            Template template = configuration.getTemplate("index.ftl");
            Map<String, String> map = objectToMap(form);
            //数据
            String title = form.title;
            //获取标题然后生成html
            //输出位置
            Writer writer = new FileWriter(pagedir+title+".html");

            //填充模板
            template.process(map,writer);
            //关闭流
            writer.close();
            return "模板填充成功!";
        } catch (Exception e) {
            return "模板填充失败!"+e.getMessage();
        }

    }





}
